<template>
  <div class="message-management">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">系统消息管理</h1>
        <p class="page-description">管理系统重要通知和消息发布</p>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          @click="showCreateDialog"
          :icon="Plus"
        >
          发布新消息
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-form">
        <el-form :model="filterForm" :inline="true">
          <el-form-item label="优先级">
            <el-select 
              v-model="filterForm.priority" 
              placeholder="选择优先级"
              clearable
              style="width: 120px"
            >
              <el-option label="紧急" value="urgent" />
              <el-option label="重要" value="important" />
              <el-option label="一般" value="normal" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="filterForm.is_active" 
              placeholder="选择状态"
              clearable
              style="width: 100px"
            >
              <el-option label="启用" :value="true" />
              <el-option label="停用" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item label="搜索">
            <el-input
              v-model="filterForm.search"
              placeholder="搜索标题或内容"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">
              搜索
            </el-button>
            <el-button @click="handleReset" :icon="Refresh">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 消息列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="messages" 
        v-loading="loading"
        stripe
        @sort-change="handleSortChange"
      >
        <el-table-column 
          prop="title" 
          label="消息标题" 
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column label="优先级" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="getPriorityTagType(row.priority)"
              size="small"
            >
              {{ getPriorityIcon(row.priority) }} {{ row.priority_display }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_active"
              @change="handleStatusChange(row)"
              :loading="row.updating"
            />
          </template>
        </el-table-column>

        <el-table-column 
          prop="created_by_name" 
          label="创建者" 
          width="120"
          show-overflow-tooltip
        />

        <el-table-column label="已读统计" width="100" align="center">
          <template #default="{ row }">
            <span class="read-stats">{{ row.read_count || 0 }}</span>
          </template>
        </el-table-column>

        <el-table-column 
          prop="created_at" 
          label="创建时间" 
          width="180"
          sortable="custom"
        >
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="过期时间" width="180">
          <template #default="{ row }">
            <span v-if="row.expire_at" :class="{ expired: row.is_expired }">
              {{ formatTime(row.expire_at) }}
            </span>
            <span v-else class="no-expire">永不过期</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                size="small" 
                @click="viewMessage(row)"
                :icon="View"
                circle
                title="查看"
              />
              <el-button 
                size="small" 
                type="primary"
                @click="editMessage(row)"
                :icon="Edit"
                circle
                title="编辑"
              />
              <el-button 
                size="small" 
                type="danger"
                @click="deleteMessage(row)"
                :icon="Delete"
                circle
                title="删除"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑消息弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑消息' : '发布新消息'"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="messageForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="消息标题" prop="title">
          <el-input
            v-model="messageForm.title"
            placeholder="请输入消息标题"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="messageForm.priority">
            <el-radio value="urgent">
              🚨 紧急
            </el-radio>
            <el-radio value="important">
              ⚠️ 重要
            </el-radio>
            <el-radio value="normal">
              ℹ️ 一般
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入消息内容，支持HTML格式"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="目标角色">
          <el-select
            v-model="messageForm.target_roles"
            multiple
            placeholder="选择目标角色（不选则发送给所有用户）"
            style="width: 100%"
          >
            <el-option
              v-for="role in availableRoles"
              :key="role.name"
              :label="role.name"
              :value="role.name"
            />
          </el-select>
          <div class="form-tip">
            不选择角色时，消息将发送给所有用户
          </div>
        </el-form-item>

        <el-form-item label="过期时间">
          <el-date-picker
            v-model="messageForm.expire_at"
            type="datetime"
            placeholder="选择过期时间（可选）"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
          <div class="form-tip">
            不设置过期时间则永不过期
          </div>
        </el-form-item>

        <el-form-item label="启用状态">
          <el-switch
            v-model="messageForm.is_active"
            active-text="启用"
            inactive-text="停用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="submitting"
          >
            {{ isEditing ? '更新' : '发布' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看消息详情弹窗 -->
    <el-dialog
      v-model="viewDialogVisible"
      :title="viewMessage?.title"
      width="600px"
    >
      <div v-if="selectedMessage" class="message-detail">
        <div class="detail-meta">
          <el-tag 
            :type="getPriorityTagType(selectedMessage.priority)"
            size="large"
          >
            {{ getPriorityIcon(selectedMessage.priority) }} {{ selectedMessage.priority_display }}
          </el-tag>
          <span class="detail-time">{{ formatTime(selectedMessage.created_at) }}</span>
        </div>
        
        <div class="detail-info">
          <div class="info-item">
            <span class="label">创建者：</span>
            <span class="value">{{ selectedMessage.created_by_name }}</span>
          </div>
          <div class="info-item" v-if="selectedMessage.expire_at">
            <span class="label">过期时间：</span>
            <span class="value" :class="{ expired: selectedMessage.is_expired }">
              {{ formatTime(selectedMessage.expire_at) }}
            </span>
          </div>
          <div class="info-item">
            <span class="label">已读统计：</span>
            <span class="value">{{ selectedMessage.read_count || 0 }} 人已读</span>
          </div>
          <div class="info-item" v-if="selectedMessage.target_roles?.length">
            <span class="label">目标角色：</span>
            <span class="value">
              <el-tag 
                v-for="role in selectedMessage.target_roles" 
                :key="role" 
                size="small"
                style="margin-right: 4px"
              >
                {{ role }}
              </el-tag>
            </span>
          </div>
        </div>
        
        <div class="detail-content" v-html="selectedMessage.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View, Edit, Delete } from '@element-plus/icons-vue'
import { adminMessageApi } from '@/api/message'
import request from '@/api/request'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// 响应式数据
const loading = ref(false)
const messages = ref([])
const availableRoles = ref([])

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 筛选表单
const filterForm = reactive({
  priority: '',
  is_active: null,
  search: ''
})

// 排序
const sortField = ref('')
const sortOrder = ref('')

// 弹窗状态
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEditing = ref(false)
const submitting = ref(false)

// 表单数据
const formRef = ref(null)
const messageForm = reactive({
  title: '',
  content: '',
  priority: 'normal',
  is_active: true,
  target_roles: [],
  expire_at: null
})

// 选中的消息
const selectedMessage = ref(null)

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' },
    { min: 1, max: 200, message: '标题长度应在1-200字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 1, max: 2000, message: '内容长度应在1-2000字符之间', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 计算属性
const getPriorityTagType = (priority) => {
  const types = {
    urgent: 'danger',
    important: 'warning',
    normal: 'info'
  }
  return types[priority] || 'info'
}

const getPriorityIcon = (priority) => {
  const icons = {
    urgent: '🚨',
    important: '⚠️',
    normal: 'ℹ️'
  }
  return icons[priority] || 'ℹ️'
}

// 方法
const loadMessages = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...filterForm
    }
    
    // 添加排序参数
    if (sortField.value && sortOrder.value) {
      params.ordering = sortOrder.value === 'descending' ? `-${sortField.value}` : sortField.value
    }

    const response = await adminMessageApi.getMessages(params)
    messages.value = response.data.results
    pagination.total = response.data.count
  } catch (error) {
    console.error('加载消息列表失败:', error)
    ElMessage.error('加载消息列表失败')
  } finally {
    loading.value = false
  }
}

const loadRoles = async () => {
  try {
    // 调用真实的角色管理API
    const response = await request.get('/auth/roles/')
    console.log('角色API响应:', response)
    
    if (response.data && response.data.results) {
      availableRoles.value = response.data.results
    } else if (response.data && Array.isArray(response.data)) {
      availableRoles.value = response.data
    } else {
      availableRoles.value = response.data || []
    }
    
    console.log('已加载角色:', availableRoles.value)
  } catch (error) {
    console.error('加载角色列表失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    ElMessage.error(`加载角色列表失败: ${error.response?.data?.detail || error.message}`)
    // API失败时设为空数组，不使用硬编码降级
    availableRoles.value = []
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadMessages()
}

const handleReset = () => {
  Object.assign(filterForm, {
    priority: '',
    is_active: null,
    search: ''
  })
  pagination.page = 1
  loadMessages()
}

const handleSortChange = ({ prop, order }) => {
  sortField.value = prop
  sortOrder.value = order
  loadMessages()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
  loadMessages()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadMessages()
}

const handleStatusChange = async (row) => {
  try {
    row.updating = true
    await adminMessageApi.updateMessage(row.id, { is_active: row.is_active })
    ElMessage.success(`消息已${row.is_active ? '启用' : '停用'}`)
  } catch (error) {
    console.error('更新状态失败:', error)
    row.is_active = !row.is_active // 回滚状态
    ElMessage.error('更新状态失败')
  } finally {
    row.updating = false
  }
}

const showCreateDialog = () => {
  isEditing.value = false
  dialogVisible.value = true
}

const viewMessage = (message) => {
  selectedMessage.value = message
  viewDialogVisible.value = true
}

const editMessage = (message) => {
  isEditing.value = true
  selectedMessage.value = message
  
  // 填充表单数据
  Object.assign(messageForm, {
    title: message.title,
    content: message.content,
    priority: message.priority,
    is_active: message.is_active,
    target_roles: message.target_roles || [],
    expire_at: message.expire_at
  })
  
  dialogVisible.value = true
}

const deleteMessage = async (message) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除消息"${message.title}"吗？此操作不可撤销。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await adminMessageApi.deleteMessage(message.id)
    ElMessage.success('删除成功')
    loadMessages()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    submitting.value = true

    if (isEditing.value) {
      await adminMessageApi.updateMessage(selectedMessage.value.id, messageForm)
      ElMessage.success('消息更新成功')
    } else {
      await adminMessageApi.createMessage(messageForm)
      ElMessage.success('消息发布成功')
    }

    dialogVisible.value = false
    loadMessages()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEditing.value ? '更新失败' : '发布失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(messageForm, {
    title: '',
    content: '',
    priority: 'normal',
    is_active: true,
    target_roles: [],
    expire_at: null
  })
  selectedMessage.value = null
}

const disabledDate = (date) => {
  return date < new Date()
}

const formatTime = (dateString) => {
  if (!dateString) return ''
  return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
}

// 生命周期
onMounted(() => {
  loadMessages()
  loadRoles()
})
</script>

<style scoped>
.message-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  .el-form {
    margin-bottom: 0;
  }
}

.table-card {
  .el-table {
    margin-bottom: 20px;
  }
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.read-stats {
  color: #409eff;
  font-weight: 600;
}

.no-expire {
  color: #909399;
  font-style: italic;
}

.expired {
  color: #f56c6c;
  text-decoration: line-through;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 消息详情样式 */
.message-detail {
  padding: 16px 0;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.detail-time {
  font-size: 13px;
  color: #909399;
}

.detail-info {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-item .label {
  min-width: 80px;
  font-weight: 600;
  color: #606266;
}

.info-item .value {
  color: #303133;
}

.detail-content {
  line-height: 1.6;
  color: #303133;
  background: #fafafa;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.detail-content :deep(p) {
  margin-bottom: 12px;
}

.detail-content :deep(p:last-child) {
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  width: 28px;
  height: 28px;
  padding: 0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 28px;
  font-size: 14px;
}

.action-buttons .el-button:hover {
  transform: scale(1.1);
  transition: transform 0.2s ease;
}

/* 响应式 */
@media (max-width: 768px) {
  .message-management {
    padding: 12px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .filter-form .el-form {
    .el-form-item {
      margin-bottom: 8px;
    }
  }

  .el-table {
    font-size: 12px;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    width: 24px;
    height: 24px;
    min-width: 24px;
    font-size: 12px;
  }
}
</style>